package com.mo.axion.handler.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.mo.axion.common.constant.CommonConstant;
import com.mo.axion.common.domain.AnchorInfo;
import com.mo.axion.common.domain.TaskInfo;
import com.mo.axion.common.enums.AnchorState;
import com.mo.axion.common.enums.ShieldType;
import com.mo.axion.common.pipeline.BusinessProcess;
import com.mo.axion.common.pipeline.ProcessContext;
import com.mo.axion.support.utils.LogUtils;
import com.mo.axion.support.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author Mo
 * @createTime 2024/4/12 2:14
 * @description 夜间屏蔽
 */
@Slf4j
@Service
public class ShieldAction implements BusinessProcess<TaskInfo> {

    private static final String NIGHT_SHIELD_BUT_NEXT_DAY_SEND_KEY = "night_shield_send";
    private static final long SECONDS_OF_A_DAY = 86400L;

    private static final int NIGHT = 8;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private LogUtils logUtils;

    @Override
    public void process(ProcessContext<TaskInfo> context) {
        TaskInfo taskInfo = context.getProcessModel();
        if (ShieldType.NIGHT_NO_SHIELD.getCode().equals(taskInfo.getShieldType())) {
            return;
        }
        //  如果在夜间
        if (LocalDateTime.now().getHour() < NIGHT) {
            //  屏蔽类型为夜间屏蔽
            if (ShieldType.NIGHT_SHIELD.getCode().equals(taskInfo.getShieldType())) {
                logUtils.print(
                        AnchorInfo.builder()
                                .state(AnchorState.NIGHT_SHIELD.getCode())
                                .bizId(taskInfo.getBizId())
                                .messageId(taskInfo.getMessageId())
                                .businessId(taskInfo.getBusinessId())
                                .idList(taskInfo.getReceiver()).build()
                );
            }
            //  屏蔽类型为夜间屏蔽次日发送，将待发送信息存入Redis中
            if (ShieldType.NIGHT_SHIELD_BUT_NEXT_DAY_SEND.getCode().equals(taskInfo.getShieldType())) {
                redisUtils.lPush(NIGHT_SHIELD_BUT_NEXT_DAY_SEND_KEY, JSON.toJSONString(taskInfo, SerializerFeature.WriteClassName), SECONDS_OF_A_DAY);
                logUtils.print(
                        AnchorInfo.builder()
                                .state(AnchorState.NIGHT_SHIELD_NEXT_SEND.getCode())
                                .bizId(taskInfo.getBizId())
                                .messageId(taskInfo.getMessageId())
                                .businessId(taskInfo.getBusinessId())
                                .idList(taskInfo.getReceiver()).build()
                );
            }
            context.setIsNeedBreak(true);
        }
    }
}
